package sort;

import java.util.Enumeration;

/**
 * @description: TODO
 * @author: mayunfei
 * @date: 2024/12/10 7:49
 */
public class MaxHeapSort {

    public static void main(String[] args) {
        int[] arr = new int[]{7,4,2,8};
        MaxHeapSort maxHeapSort = new MaxHeapSort();
        maxHeapSort.sortArray(arr);
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }
    }

    public int[] sortArray(int[] nums) {
        buildMaxHeap(nums);
        int len = nums.length;
        for (int i = 0; i < len; i++) {
            swap(nums, 0, len - i - 1);
            motifyMaxHeap(nums, len - i - 1, 0);
        }
        return nums;
    }

    private void buildMaxHeap(int[] nums) {
        for (int i = nums.length / 2 - 1; i >= 0; i--) {
            motifyMaxHeap(nums, nums.length, i);
        }
    }

    private void motifyMaxHeap(int[] nums, int heapSize, int i) {
        int l = 2 * i + 1;
        int r = 2 * i + 2;
        int largest = i;
        if (l < heapSize && nums[l] > nums[largest]) largest = l;
        if (r < heapSize && nums[r] > nums[largest]) largest = r;
        if (largest != i) {
            swap(nums, i, largest);
            motifyMaxHeap(nums, heapSize, largest);
        }
    }

    private void swap(int[] nums, int i, int j) {
        int tmp = nums[i];
        nums[i] = nums[j];
        nums[j] = tmp;
    }
}
